<template>
  <div id="app" :class="`${showAiHead?'showAiHead':''}`">
    <ai-head v-if="showAiHead"></ai-head>
    <router-view class="main-container"/>
  </div>
</template>

<script>
import { registerInformApi, invokeAsyncAPi } from '@/xz-fn.js'
import AiHead from '@/components/ai-head'
import { mapGetters } from 'vuex'
import listTable from '@/db/listTable'
export default {
  name: 'App',
  async created () {
    if (process.env.VUE_APP_NAME === 'xz') {
      invokeAsyncAPi('HtmlPaintComplete', { CompleteUrl: location.href })
    } else if (['yueshu', 'dll', 'repairmaster'].includes(process.env.VUE_APP_NAME)) {
      this.$xz('xz_set_window_size', process.env.VUE_APP_WINDOW_NAME, 440, 750)
      this.$xz('xz_page_load_finished', process.env.VUE_APP_WINDOW_NAME)
    }
    await this.int()
    if (process.env.VUE_APP_BUY_TYPE === 'energy') {
      this.$store.dispatch('chat/getFnPrice')
      this.$store.dispatch('system/getBtnCfg')
    }
  },
  components: {
    AiHead
  },
  computed: {
    ...mapGetters(['hasLogin', 'userInfo']),
    userId () {
      return this.userInfo.userid || ''
    },
    isXz () {
      return process.env.VUE_APP_NAME === 'xz'
    },
    isYueShu () {
      return process.env.VUE_APP_NAME === 'yueshu'
    },
    isDll () {
      return process.env.VUE_APP_NAME === 'dll'
    },
    isRepairMaster () {
      return process.env.VUE_APP_NAME === 'repairmaster'
    },
    showAiHead () {
      return this.isYueShu || this.isDll
    }
  },
  watch: {
    userId () {
      this.initGroupList()
    }
  },
  mounted () {
    if (this.isXz) {
      // 登录状态改变
      registerInformApi('Notify_UserStatus', async (data) => {
        const { LogonStatus, Logon } = data
        if (LogonStatus === 3 || Logon) {
          this.int().then(() => {
            window.dispatchEvent(new Event('loginChangeLoaded'))
          })
        } else {
          this.$store.dispatch('user/resetUserInfo')
          this.$store.dispatch('history/clear')
        }
      })
      // 权益变更
      registerInformApi('Notify_UserRightChange', async () => {
        this.payChange()
      })
      registerInformApi('inform_power_result', () => {
        this.payChange()
      })
      this.$xzReg('inform_query_remind', res => {
        this.setGroupList(res)
      })
      this.$xzReg('inform_add_remind', res => {
        this.$xz('BroadcastData', 'aichat:onTodoListChange')
        this.$PsMessage('待办创建成功！')
      })
      this.$xzReg('Notify_BroadcastData', this.broadcastData)
    } else if (this.isYueShu) {
      registerInformApi('inform_pay_result', async () => {
        this.payChange()
      })

      // ai token变更
      registerInformApi('inform_update_ai_token', async () => {
        this.int()
      })

      registerInformApi('inform_login', this.loginChange)
    } else if (this.isDll || this.isRepairMaster) {
      registerInformApi('inform_event', (res) => {
        if (res.type === 'login') {
          this.loginChange().then(() => {
            window.dispatchEvent(new Event('loginChangeLoaded'))
          })
        } else if (res.type === 'pay') {
          this.payChange()
        }
      })
    }
  },
  methods: {
    broadcastData (info) {
      const data = info.BroadcastData
      const arr = data.split(':')
      const win = arr[0]
      const fn = this[arr[1]]
      if (win === 'aichat') return
      if (typeof fn === 'function') {
        fn(arr[2])
      }
    },
    onGroupListChange () { // todo别的窗口调用
      this.initGroupList()
    },
    onAiTokenChange () { // todo别的窗口调用
      this.$store.dispatch('user/getUserRights')
    },
    initGroupList () {
      listTable.get(`opType = 1 and userId="${this.userId}" GROUP BY clientId`)

      // this.$store.dispatch('todo/setGroupList', list)
      // this.groupValue = this.groupList.find(it => it.clientId === '')
    },
    setGroupList (res) {
      try {
        const list = JSON.parse(res)
        list.forEach((item, index) => {
          if (item.isDefault === 1) {
            item.clientId = ''
          }
          item.index = index
        })
        this.$store.dispatch('todo/setGroupList', list)
      } catch (e) {}
    },
    async payChange () {
      await this.int()
      this.$store.dispatch('system/setVipGuide', { status: false, title: '' })
    },
    async loginChange () {
      await this.$store.dispatch('user/getUserInfo')
      if (this.hasLogin) {
        await this.int()
      } else {
        this.$store.dispatch('user/resetUserInfo')
        this.$store.dispatch('history/clear')
      }
    },
    async int () {
      await this.$store.dispatch('user/getUserInfo')
      if (this.hasLogin) {
        this.$store.dispatch('user/getUserRights')
        this.$store.dispatch('user/getMemberInfos')
      }
      await this.$store.dispatch('chat/getModels', {})
      this.$store.dispatch('chat/getModels', { type: 'knowledge' })
    }
  }
}
</script>
<style lang="scss" scoped>
#app.showAiHead{
  background: rgba(0,0,0,1);
}
</style>
